//
//  AISMediaGroupingTypeTableViewController.m
//  UpnpPlaylist
//
//  Created by Ares on 12/7/15.
//  Copyright © 2015 Ares. All rights reserved.
//

#import "AISMediaPickerViewController.h"

@interface AISMediaPickerViewController () <AISMediaPickerViewControllerDelegate, UISearchBarDelegate> {
    NSArray *groupingTypeIconArray;
    NSArray *itemArray;
}

@end

@implementation AISMediaPickerViewController

+ (AISMediaPickerViewController *)viewControllerWithAISMediaPicker {
    UIStoryboard *mediaStoryboard = [UIStoryboard storyboardWithName:@"AISMediaPickerStoryboard" bundle:nil];
    AISMediaPickerViewController *mediaTableViewController = [mediaStoryboard instantiateViewControllerWithIdentifier:@"MediaTableViewControllerStoryboard"];
    
    return mediaTableViewController;
}

- (void)viewDidLoad {
    [super viewDidLoad];
    
    // Uncomment the following line to preserve selection between presentations.
    // self.clearsSelectionOnViewWillAppear = NO;
    
    // Uncomment the following line to display an Edit button in the navigation bar for this view controller.
    // self.navigationItem.rightBarButtonItem = self.editButtonItem;
    
    [self.btnDone setHidden:self.hiddenCancelButton];
    itemArray = [self itemsForMediaItemType:self.itemType];
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

#pragma mark Private Functions

- (NSArray *)itemsForMediaItemType:(MediaItemType)itemType {
    NSArray *retArray = nil;
    MPMediaQuery *mediaQuery = nil;
    switch (itemType) {
            // for grouping type page
        case MIT_GROUPING_TYPE:
        {
            groupingTypeIconArray = @[@"Artists", @"Albums", @"Songs", @"Genres", @"Playlists"];
            retArray = @[@"Artists", @"Albums", @"Songs", @"Genres", @"Playlists"];
            break;
        }
            
            // for collections page
        case MIT_ARTIST_COLLECTIONS:
        {
            mediaQuery = [MPMediaQuery artistsQuery];
            retArray = [mediaQuery collections];
            break;
        }
        case MIT_ALBUM_COLLECTIONS:
        {
            mediaQuery = [MPMediaQuery albumsQuery];
            retArray = [mediaQuery collections];
            break;
        }
        case MIT_GENRE_COLLECTIONS:
        {
            mediaQuery = [MPMediaQuery genresQuery];
            retArray = [mediaQuery collections];
            break;
        }
        case MIT_PLAYLIST_COLLECTIONS:
        {
            mediaQuery = [MPMediaQuery playlistsQuery];
            retArray = [mediaQuery collections];
            break;
        }
            
            // For songs page
        case MIT_SONGS_COLLECTIONS:
        {
            mediaQuery = [MPMediaQuery songsQuery];
            self.mediaItemCollection = [MPMediaItemCollection collectionWithItems:[mediaQuery items]];
            retArray = [self.mediaItemCollection items];
            break;
        }
        case MIT_SONG_ITEMS:
        {
            retArray = [self.mediaItemCollection items];
            break;
        }
        default:
            break;
    }
    
    return retArray;
}

#pragma mark Action Selector
- (IBAction)btnDoneTapped:(id)sender {
    if ([self.delegate respondsToSelector:@selector(aisMediaTableViewControllerDidCancel)]) {
        [self.delegate aisMediaTableViewControllerDidCancel];
    }
}

#pragma mark - Table view data source

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
    return 1;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    return [itemArray count] + 1;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    UITableViewCell *cell = nil;
    if (0 == indexPath.row) { // for search
        cell = [tableView dequeueReusableCellWithIdentifier:@"IdentifierForSearchCell" forIndexPath:indexPath];
        
        UISearchBar *searchBar = (UISearchBar *)[cell viewWithTag:10];
        [searchBar setDelegate:self];
        
    } else if (MIT_GROUPING_TYPE == self.itemType) { // for grouping type page
        cell = [tableView dequeueReusableCellWithIdentifier:@"IdentifierForGroupingTypeCell" forIndexPath:indexPath];
        
        UIImageView *ivIcon = (UIImageView *)[cell viewWithTag:10];
        UILabel *lbTitle = (UILabel *)[cell viewWithTag:11];
        
        [ivIcon setImage:[UIImage imageNamed:[groupingTypeIconArray objectAtIndex:indexPath.row -1]]];
        [lbTitle setText:[itemArray objectAtIndex:(indexPath.row - 1)]];
    } else {
        cell = [tableView dequeueReusableCellWithIdentifier:@"IdentifierForMediaItemCell" forIndexPath:indexPath];
        
        UIImageView *ivIcon = (UIImageView *)[cell viewWithTag:10];
        UILabel *lbTitle = (UILabel *)[cell viewWithTag:11];
        UILabel *lbSubTitle = (UILabel *)[cell viewWithTag:12];
        
        if (self.itemType >= MIT_ARTIST_COLLECTIONS && self.itemType <= MIT_PLAYLIST_COLLECTIONS && self.itemType != MIT_SONGS_COLLECTIONS) { // for collections page
            MPMediaItemCollection *itemCollection = [itemArray objectAtIndex:(indexPath.row - 1)];
            MPMediaItem *item = [itemCollection representativeItem];
            [ivIcon setImage:[item.artwork imageWithSize:CGSizeMake(44, 44)]];
            
            switch (self.itemType) {
                    // for collections
                case MIT_ARTIST_COLLECTIONS:
                {
                    [lbTitle setText:item.artist];
                    [lbSubTitle setText:[NSString stringWithFormat:@"%ld Song", (unsigned long)[[itemCollection items] count]]];
                    break;
                }
                case MIT_ALBUM_COLLECTIONS:
                {
                    [lbTitle setText:item.albumTitle];
                    [lbSubTitle setText:item.albumArtist];
                    break;
                }
                case MIT_GENRE_COLLECTIONS:
                {
                    [lbTitle setText:item.genre];
                    [lbSubTitle setText:[NSString stringWithFormat:@"%ld Song", (unsigned long)[[itemCollection items] count]]];
                    break;
                }
                case MIT_PLAYLIST_COLLECTIONS:
                {
                    NSString *playlistName =[itemCollection valueForProperty:MPMediaPlaylistPropertyName];
                    [lbTitle setText:playlistName];
                    [lbSubTitle setText:[NSString stringWithFormat:@"%ld Song", (unsigned long)[[itemCollection items] count]]];
                    break;
                }
                default:
                    break;
            }
        } else { // for songs page
            MPMediaItem *item = [itemArray objectAtIndex:(indexPath.row - 1)];
            [ivIcon setImage:[item.artwork imageWithSize:CGSizeMake(44, 44)]];
            [lbTitle setText:item.title];
            [lbSubTitle setText:item.artist];
        }
    }
    
    return cell;
}

/*
// Override to support conditional editing of the table view.
- (BOOL)tableView:(UITableView *)tableView canEditRowAtIndexPath:(NSIndexPath *)indexPath {
    // Return NO if you do not want the specified item to be editable.
    return YES;
}
*/

/*
// Override to support editing the table view.
- (void)tableView:(UITableView *)tableView commitEditingStyle:(UITableViewCellEditingStyle)editingStyle forRowAtIndexPath:(NSIndexPath *)indexPath {
    if (editingStyle == UITableViewCellEditingStyleDelete) {
        // Delete the row from the data source
        [tableView deleteRowsAtIndexPaths:@[indexPath] withRowAnimation:UITableViewRowAnimationFade];
    } else if (editingStyle == UITableViewCellEditingStyleInsert) {
        // Create a new instance of the appropriate class, insert it into the array, and add a new row to the table view
    }   
}
*/

/*
// Override to support rearranging the table view.
- (void)tableView:(UITableView *)tableView moveRowAtIndexPath:(NSIndexPath *)fromIndexPath toIndexPath:(NSIndexPath *)toIndexPath {
}
*/

/*
// Override to support conditional rearranging of the table view.
- (BOOL)tableView:(UITableView *)tableView canMoveRowAtIndexPath:(NSIndexPath *)indexPath {
    // Return NO if you do not want the item to be re-orderable.
    return YES;
}
*/

#pragma mark - UITableViewDelegate

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
    if (0 == indexPath.row) {
        return;
    }
    
    if (MIT_SONGS_COLLECTIONS == self.itemType || self.itemType > MIT_PLAYLIST_COLLECTIONS) { // for songs page
        if ([self.delegate respondsToSelector:@selector(aisMediaPicker:didPickMediaItems:andSelectedIndex:)]) {
            [self.delegate aisMediaPicker:self didPickMediaItems:self.mediaItemCollection andSelectedIndex:(indexPath.row - 1)];
        }
        
        return;
    }
    
    AISMediaPickerViewController *mediaTableViewController = [AISMediaPickerViewController viewControllerWithAISMediaPicker];
    
    if (MIT_GROUPING_TYPE == self.itemType) { // for grouping type page
        [mediaTableViewController setItemType:indexPath.row];
    } else { // for collections page
        [mediaTableViewController setItemType:MIT_SONG_ITEMS];
        MPMediaItemCollection *itemCollection = [itemArray objectAtIndex:(indexPath.row - 1)];
        [mediaTableViewController setMediaItemCollection:itemCollection];
    }
    [mediaTableViewController setHiddenCancelButton:self.hiddenCancelButton];
    [mediaTableViewController setDelegate:self];
    [self.navigationController pushViewController:mediaTableViewController animated:YES];
}

#pragma mark - AISMediaPickerViewControllerDelegate

- (void)aisMediaPicker:(AISMediaPickerViewController *)mediaPicker didPickMediaItems:(MPMediaItemCollection *)mediaItemCollection andSelectedIndex:(NSInteger)index {
    if ([self.delegate respondsToSelector:@selector(aisMediaPicker:didPickMediaItems:andSelectedIndex:)]) {
        [self.delegate aisMediaPicker:self didPickMediaItems:mediaItemCollection andSelectedIndex:index];
    }
}

- (void)aisMediaTableViewControllerDidCancel {
    if ([self.delegate respondsToSelector:@selector(aisMediaTableViewControllerDidCancel)]) {
        [self.delegate aisMediaTableViewControllerDidCancel];
    }
}

#pragma mark - UISearchBarDelegate

- (void)searchBarSearchButtonClicked:(UISearchBar *)searchBar {
    NSString *musicName = searchBar.text;
    if (nil != musicName) {
        MPMediaPropertyPredicate *predicate = [MPMediaPropertyPredicate predicateWithValue:musicName forProperty:MPMediaItemPropertyTitle comparisonType:MPMediaPredicateComparisonContains];
        
        MPMediaQuery *mediaQuery = [[MPMediaQuery alloc] init];
        [mediaQuery setFilterPredicates:[[NSSet alloc] initWithObjects:predicate, nil]];
        
        [self setItemType:MIT_SONG_ITEMS];
        self.mediaItemCollection = [MPMediaItemCollection collectionWithItems:[mediaQuery items]];
        itemArray = [mediaQuery items];
        
        [self.tableView reloadData];
    }
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
